import json
import traceback
import logging
from datetime import datetime, timedelta
from django.db import transaction
from django.http import JsonResponse
from django.db.models import Q, Sum
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from django.views import View
from Model.models import Contract, Package, District, Subdistrict, Community, Address, IncomeDetail, IncomeTotal
from Model.modelsView import ContractInfo
from tools.Tools import getCurrentUser, createHandleLog, getRandomPassword, getLetterByCity, createFile
from tools.DateTools import getEndDateByDurationAndPackage
from tools.createBusiness import createIncomeTotal, createIncomeDetail, createAuthInfo, updateEquipment

res = dict()
logger_info = logging.getLogger('info')


class ContractView(View):
    res.clear()

    def get(self, request, *args, **kwargs):
        current = request.GET.get("current")
        pageSize = request.GET.get("pageSize")
        account_number = request.GET.get("account_number")
        linkman = request.GET.get("linkman")
        link_telephone = request.GET.get("link_telephone")
        install_address = request.GET.get("install_address")
        dataInfo = ContractInfo.objects.all()
        if account_number is not None and account_number != '':
            dataInfo = dataInfo.filter(account_number=account_number)
        if linkman is not None and linkman != '':
            dataInfo = dataInfo.filter(linkman__contains=linkman)
        if link_telephone is not None and link_telephone != '':
            dataInfo = dataInfo.filter(link_telephone__contains=link_telephone)
        if install_address is not None and install_address != '':
            dataInfo = dataInfo.filter(install_address__contains=install_address)
        total = dataInfo.__len__()
        data = list(dataInfo.values()[int(pageSize) * int(current) - int(pageSize):int(pageSize) * int(current)])
        res['status'] = 200
        res['data'] = data
        res['total'] = total
        res['current'] = current
        res['pageSize'] = pageSize
        res['messages'] = '请求成功'
        return JsonResponse(res, status=HTTP_200_OK)

    @transaction.atomic
    def post(self, request, *args, **kwargs):
        try:
            img = request.FILES.get('img')
            client_id = request.POST.get('client_id')
            linkman = request.POST.get('linkman')
            link_telephone = request.POST.get('link_telephone')
            district = request.POST.get('district')
            address = request.POST.get('address')
            agreement = request.POST.get('agreement')
            community = request.POST.get('community')
            detail_address = request.POST.get('detail_address')
            equipment = request.POST.get('equipment')
            equipment = json.loads(equipment) if equipment != 'undefined' else list()
            memo = request.POST.get('memo')
            service_package = request.POST.get('service_package')
            initial_money = request.POST.get('initial_money')
            subdistrict = request.POST.get('subdistrict')
            start_date = request.POST.get('start_date')
            installer = request.POST.get('installer')
            createDate = Contract.objects.create()
            createDate.contract_id = createDate.id
            createDate.client_id = client_id
            createDate.linkman = linkman.strip()
            createDate.link_telephone = link_telephone
            createDate.service_package = service_package
            createDate.start_date = start_date
            createDate.state = 1
            createDate.renew_state = 0
            createDate.end_date = getEndDateByDurationAndPackage(service_package, start_date)
            createDate.district = district
            createDate.subdistrict = subdistrict
            createDate.community = community
            createDate.address = address
            createDate.detail_address = detail_address
            district_name = District.objects.get(district_id=district).name
            city = District.objects.get(district_id=district).city
            subdistrict_name = Subdistrict.objects.get(subdistrict_id=subdistrict).name
            community_name = Community.objects.get(community_id=community).name
            address_name = Address.objects.get(address_id=address).name
            createDate.install_address = district_name + subdistrict_name + community_name + address_name + detail_address
            createDate.agreement = agreement
            createDate.memo = memo
            createDate.installer = installer
            createDate.account_number = getLetterByCity(city) + str(createDate.id + 100).zfill(8)
            createDate.account_password = getRandomPassword()
            createDate.operator = getCurrentUser(request)
            createDate.create_date = datetime.now()
            file_path = createFile(createDate.account_number, img, '协议单')
            createDate.agreement_img = file_path
            package_price = Package.objects.get(package_id=service_package).package_price
            totalId = createIncomeTotal(createDate.contract_id, client_id, 1, str(createDate.operator), memo)

            # 套餐费用
            createIncomeDetail(totalId, createDate.contract_id, 1, package_price)
            # 初装费用
            createIncomeDetail(totalId, createDate.contract_id, 2, initial_money)
            # 设备明细
            if equipment.__len__() > 0:
                for e in equipment:
                    createIncomeDetail(totalId, createDate.contract_id, 4, float(e['money']),
                                       equipmentType=e['equipment_type'], code=e['code'])
                    updateEquipment(1, e['code'], createDate.account_number)
            createAuthInfo(createDate.account_number, createDate.account_password, createDate.service_package,
                           str(createDate.end_date)[:10])

            createDate.save()
            total_sum = IncomeDetail.objects.filter(total_id=totalId).aggregate(sum=Sum('amount'))['sum']
            total = IncomeTotal.objects.get(total_id=totalId)
            total.amount = total_sum
            total.save()
            createDate.save()
            res['status'] = 200
            res['message'] = '创建成功'
            createHandleLog('创建合同', str(getCurrentUser(request)), list(request.POST.items()))
            logger_info.info(
                f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《创建合同》权限 新增内容 {list(request.POST.items())}')
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            res['status'] = 400
            res['messages'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def put(self, request, *args, **kwargs):
        pass

    @transaction.atomic
    def delete(self, request, *args, **kwargs):
        pass
